from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.core.cache import caches
from apps.websocket.update_data import TotalConsumerUpdateData
from apps.websocket.groupCustomers import WS_CACHE
# Create your views here.

def call_back(result):
    print('回调的结果')
    if result:
        print('消息发送成功')
    else:
        print('消息发送失败')
def send_message_to_consumer(channel_name, message):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.send)(
        channel_name,
        {
            "type": "forward.message",
            "text": message,
        }
    )
    print('执行了')
class TestView(APIView):
     def get(self, request):
        cache = caches['memory']
        msg = request.GET.get('msg')
        key = request.GET.get('key')
        channel_name = WS_CACHE.CACHE.get(key)
        print(channel_name,'拿到获取到的channel_name')
        try:
            send_message_to_consumer(channel_name, msg)
        except Exception as e:
            print(e)

            return Response({'code':400,'msg':'发送失败'})
        return Response({"code": 200,'msg':'发送成功'})


class UpdateUserInfo(APIView):
    def get(self,request):
        TotalConsumerUpdateData.user_info()
        TotalConsumerUpdateData.alert_info()
        return Response({'code':200,'msg':'推送数据成功'})